package com.mf.controller;

import com.mf.entity.Task;
import com.mf.entity.TaskDetail;
import com.mf.entity.TaskDetailDto;
import com.mf.exception.CustomExceptionHandler;
import com.mf.service.impl.TaskDetailServiceImpl;
import com.mf.service.impl.TaskServiceImpl;
import com.mf.utils.Result;
import com.mf.verify.verifyField;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 任务明细 前端控制器
 * </p>
 *
 * @author mf
 * @since 2024-04-13
 */
@RestController
@RequestMapping("/task/detail")
@Tag(name = "任务明细")
public class TaskDetailController {
    @Resource
    private  TaskDetailServiceImpl taskDetailService;

    @Resource
    private TaskServiceImpl taskService;

    @GetMapping("/delete")
    @Operation(summary = "删除任务明细")
    public Result<Boolean> delete(@RequestParam("id") Integer id) {
        return Result.success(taskDetailService.removeById(id));
    }

    @PostMapping("/deleteBatch")
    @Operation(summary = "批量删除")
    public Result<Boolean> deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(taskDetailService.removeByIds(ids));
    }

    @GetMapping("/findByTId")
    @Operation (summary = "根据任务id查询")

    public Result<List<TaskDetail>> findByTId(@RequestParam("id") Integer id) {
        return Result.success(taskDetailService.getByTId(id));
    }

    @PostMapping("/findByTidAndDate")
    @Operation(summary = "根据任务id和日期查询")
    public Result<List<TaskDetail>> findByTidAndDate(@RequestBody TaskDetailDto taskDetailDto) {
        return Result.success(taskDetailService.getByTIdAndDate(taskDetailDto));
    }


    @PostMapping("/add")
    @Operation(summary = "新增任务明细")
    public Result<Boolean> add(@RequestBody TaskDetail taskDetail) {
        getTask(taskDetail,"startTime");
        return Result.success(taskDetailService.save(taskDetail));
    }

    @PostMapping("/update")
    @Operation(summary = "更新任务明细")
    public Result<Boolean> update(@RequestBody TaskDetail taskDetail){
        getTask(taskDetail,"endTime");
        return Result.success(taskDetailService.updateById(taskDetail));
    }




    private void getTask(@RequestBody TaskDetail taskDetail,String timeField) {
        final Task task = taskService.getById(taskDetail.getTId());
        List<String> checkNames = new ArrayList<>(List.of("tId"));

        if(null == task){
            throw new CustomExceptionHandler("任务不存在");
        }

        if(!timeField.isEmpty()){
            checkNames.add(timeField);
        }
        verifyField.isEmpty(taskDetail,checkNames);
    }



}
